package com.dq.controller.app.login;

import com.dq.context.Constant;
import com.dq.context.event.user.UserLostPwdEvent;
import com.dq.domain.sys.role.SysRole;
import com.dq.domain.sys.role.SysUserRole;
import com.dq.domain.sys.user.user.BossUser;
import com.dq.domain.sys.user.user.base.SysUser;
import com.dq.exception.customException.AdminException;
import com.dq.controller.api.merchant.in.request.LoginRequest;
import com.dq.controller.api.merchant.in.request.LostPwdRequest;
import com.dq.vo.Vo;
import com.dq.domain.sys.user.user.StaffUser;
import com.dq.service.AllService;
import com.dq.shiro.MyToken;
import com.dq.utils.EditCheckUtil;
import com.dq.utils.PasswordUtil;
import com.dq.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author cf
 */
@Api(description = "APP登陆")
@RestController
@RequestMapping("/app/login/")
public class AppLoginController extends AllService {
    @PostMapping("signIn")
    @ApiOperation("APP登陆")
    public Vo signIn(@RequestBody LoginRequest loginRequest)throws AdminException {
        if( StringUtils.isBlank(loginRequest.getUsername()) || StringUtils.isBlank(loginRequest.getPassword())){
            throw new AdminException("输入账号或密码");
        }
        BossUser bossUser = bossUserRepository.findByDeletedFalseAndUsernameAndStatus(loginRequest.getUsername(), SysUser.Status.on);
        if (null == bossUser) {
            throw new AdminException("账号不存");
        }
        if(!PasswordUtil.verify(loginRequest.getPassword(), bossUser.getPassword())){
            throw new AdminException("密码不正确");
        }
        List<Long> roleId = new ArrayList<>();
        List<String> roleName = new ArrayList<>();
        List<String> roleCode = new ArrayList<>();
        boolean judge = true;
        List<SysUserRole> userRoles = sysUserRoleRepository.findByDeletedFalseAndSysUserAndSysRoleStatus(bossUser, SysRole.Status.on);
        if(userRoles != null && userRoles.size() > 0) {
            for (SysUserRole userRole : userRoles) {
//                if(userRole.getSysRole().getCode().equals(Constant.ROLE_CODE_LIST.get(3))
//                || userRole.getSysRole().getCode().equals(Constant.ROLE_CODE_LIST.get(4))) {
                    judge = false;
                    break;
//                }
            }
            for (SysUserRole userRole : userRoles) {
                roleId.add(userRole.getSysRole().getId());
                roleName.add(userRole.getSysRole().getRoleName());
                roleCode.add(userRole.getSysRole().getCode());
            }
        }
        if(judge) {
            throw new AdminException("用户无角色权限");
        }


        String token = tokenService.createToken(bossUser);
        Subject subject = SecurityUtils.getSubject();
        AuthenticationToken token1 = new MyToken(token);
        subject.login(token1);
        BossUser.LoginVo userVo = bossUser.toLoginVo();
        userVo.setToken(token);
        userVo.setRoleId(roleId);
        userVo.setRoleName(roleName);
        userVo.setRoleCode(roleCode);
        return new Vo(userVo);
    }

    @GetMapping("lostPwd/sendSms/{mobile}")
    @ApiOperation("忘记密码, 发送验证码")
    public Vo lostPwdSendSms(@PathVariable String mobile)throws AdminException {
        if(!EditCheckUtil.isMobileNO(mobile)){
            throw new AdminException("手机号格式不正确");
        }
        BossUser bossUser = bossUserRepository.findByDeletedFalseAndMobileAndStatus(mobile, SysUser.Status.on);
        if(null == bossUser){
            throw new AdminException("手机号无对应用户");
        }

        String smsCode = RandomUtil.getNumber(6);
        Map<String, Object> map = new HashMap<>(16);
        map.put("phone", mobile);
        map.put("smsCode", smsCode);
        eventPublisher.publishEvent(new UserLostPwdEvent(map));
        shiroService.setSmsCaptchaCache(smsCode ,mobile);
        return new Vo(HttpStatus.OK);
    }
    @PostMapping("lostPwd")
    @ApiOperation("忘记密码, 根据验证码修改密码")
    public Vo lostPwd(@RequestBody @Valid LostPwdRequest lostPwdRequest)throws AdminException {
        if(!EditCheckUtil.isMobileNO(lostPwdRequest.getPhone())){
            throw new AdminException("手机号格式不正确");
        }

        BossUser bossUser = bossUserRepository.findByDeletedFalseAndMobileAndStatus(lostPwdRequest.getPhone(), SysUser.Status.on);
        if(null == bossUser){
            throw new AdminException("手机号无对应用户");
        }

        String cacheSms = shiroService.getSmsCaptchaCache(lostPwdRequest.getPhone());
        if(!cacheSms.equals(lostPwdRequest.getSmdCode())){
            throw new AdminException("验证码不正确");
        }
        bossUser.setPassword(PasswordUtil.generate(lostPwdRequest.getNewPwd()));
        bossUserRepository.save(bossUser);
        return new Vo(HttpStatus.OK);
    }
}
